package com.aerilys.taskboard.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.aerilys.taskboard.client.NoteService;
import com.aerilys.taskboard.shared.FieldVerifier;
import com.aerilys.taskboard.shared.Note;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class NoteServiceImpl extends RemoteServiceServlet implements NoteService
{

  public String greetServer(Note note) throws IllegalArgumentException
  {
    // Verify that the input is valid.
    if (!FieldVerifier.isValidName(note.getNom()))
    {
      // If the input is not valid, throw an IllegalArgumentException back to
      // the client.
      throw new IllegalArgumentException("Note name must be at least 4 characters long");
    }

    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    if (user != null)
    {
      // Escape data from the client to avoid cross-site script vulnerabilities.
      note.setNom(escapeHtml(note.getNom()));

      Key guestbookKey = KeyFactory.createKey("Notes", user.getNickname());
      note.setDateCreation(new Date());
      Entity greeting = new Entity("Note", guestbookKey);
      greeting.setProperty("user", user);
      greeting.setProperty("nom", note.getNom());
      greeting.setProperty("description", note.getDescription());

      DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
      datastore.put(greeting);

      return "Hello, " + note.getNom();
    }
    else
      return "Echec de l'authentification";
  }

  @Override
  public List<Note> getNotes()
  {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if (user != null)
    {
      DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
      Key guestbookKey = KeyFactory.createKey("Notes", user.getNickname());
      
      Query query = new Query("Note", guestbookKey);
      List<Entity> notes = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
      
      List<Note> listeNotes = new ArrayList<Note>();
      for(Entity note : notes)
      {
        Note tmp = new Note();
        tmp.setNom(note.getProperty("nom").toString());
        tmp.setDescription(note.getProperty("description").toString());
        listeNotes.add(tmp);
      }
      
      return listeNotes;
    }
    else
      return null;
  }

  /**
   * Escape an html string. Escaping data received from the client helps to
   * prevent cross-site script vulnerabilities.
   * 
   * @param html the html string to escape
   * @return the escaped string
   */
  private String escapeHtml(String html)
  {
    if (html == null)
    {
      return null;
    }
    return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
  }

}
